<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="教练姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入教练姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="技术等级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择教练等级">
          <el-option
            v-for="item in coachGrade"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            @keyup.enter.native="handleQuery"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >添加教练
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="coachList">
      <el-table-column label="教练姓名" align="center" prop="name"/>
      <el-table-column label="头像" align="center" prop="avatar">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatar" :width="80" :height="80"/>
        </template>
      </el-table-column>
      <el-table-column label="技能认证" align="center" prop="skilled">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.skilled" :src="scope.row.skilled" :width="80" :height="80"/>
          <span v-else class="">未上传证书</span>
        </template>
      </el-table-column>
      <el-table-column label="擅长" align="center" prop="major"/>
      <el-table-column label="课时费/元" align="center">
        <template slot-scope="scope">
          <span>{{ (scope.row.price) / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上线/下线" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch :width="34" v-model="scope.row.status" @change="changStatus($event, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="技术等级" align="center" prop="grade">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.grade==1">一级</el-tag>
          <el-tag type="success" v-if="scope.row.grade==2">二级</el-tag>
          <el-tag type="warning" v-if="scope.row.grade==3">三级</el-tag>
          <el-tag type="danger" v-if="scope.row.grade==4">四级</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评分" align="center" prop="score"/>
      <el-table-column label="所属场馆" align="center" prop="stadiumId">
        <template slot-scope="scope">
          <span v-if="scope.row.stadiumId==2">东湖昇光店</span>
        </template>
      </el-table-column>
      <el-table-column label="入驻时间" align="center" prop="createAt">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortValue">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.sortValue" controls-position="right" size="mini" @change="sortChange(scope.row.id,$event)" :min="1" :max="999"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleInfo(scope.row)"
          >查看详情
          </el-button>
<!--          <el-button-->
<!--            icon="el-icon-coordinate"-->
<!--            v-if="scope.row.status == 0"-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            style="color: #67C23A"-->
<!--            @click="examineCoach(scope.row.id,1)" Refused-->
<!--          >通过-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            icon="el-icon-coordinate"-->
<!--            v-if="scope.row.status==0"-->
<!--            size="mini"-->
<!--            style="color: #E6A23C"-->
<!--            type="text" @click="examineCoach(scope.row.id,-1)"-->
<!--          >不通过-->
<!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            style="color: #F56C6C"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教练对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="教练姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入教练姓名"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码"/>
        </el-form-item>
        <el-form-item label="课时费" prop="price">
          <el-input v-model="form.price" placeholder="请输入课时费"/>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <image-upload v-model="form.avatar" :limit="1"></image-upload>
        </el-form-item>
        <el-form-item label="个人标签" prop="label">
          <el-select
            :multiple-limit="3"
            v-model="form.label"
            readonly
            filterable
            :multiple="true"
            allow-create
            default-first-option
            placeholder="请选择个人标签,可自定义标签"
            style="width:600px "
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div class="prompt">请选择技能标签，最多可选3个，也可以自己填写，与个人标签形成补充</div>
        </el-form-item>
        <el-form-item label="技能认证" prop="skilled">
          <image-upload v-model="form.skilled"></image-upload>
        </el-form-item>
        <el-form-item label="教学视频" prop="video">
          <el-upload :file-list="videoFileList" :action="videoAction"
                     :before-upload="videoBeforeUpload" :on-success="videoUploadSuccess" :on-remove="videoDelete" :on-error="videoUploadError" :limit="1" accept=".mp4"
          >
            <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
          </el-upload>
          <div>请上传短视频，格式为mp4，大小不超过10M</div>
        </el-form-item>
        <el-form-item label="获得荣誉" prop="honor">
          <el-input v-model="form.honor" placeholder="获得荣誉" maxlength="200"/>
        </el-form-item>
        <el-form-item label="擅长技能" prop="major">
          <el-input v-model="form.major" placeholder="请输入擅长技能"/>
        </el-form-item>
        <el-form-item label="上课风格" prop="style">
          <el-input v-model="form.style" placeholder="请输入上课风格"/>
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-input v-model="form.score" placeholder="获得荣誉" maxlength="200"/>
        </el-form-item>
        <el-form-item label="技术等级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择教练等级">
            <el-option
              v-for="item in coachGrade"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属场馆" prop="stadiumId">
          <el-select v-model="form.stadiumId" placeholder="请选择所属场馆">
            <el-option
              v-for="item in stadiumList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简单介绍" prop="introduce">
          <el-input v-model="form.introduce" placeholder="简单介绍" maxlength="200"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="saveDraft">保存草稿</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-descriptions title="教练信息" column="4">
        <el-descriptions-item label="姓名">{{ form.name }}</el-descriptions-item>
        <el-descriptions-item label="头像">
          <template>
            <image-preview :src="form.avatar" :width="80" :height="80"/>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="技能证书">
          <template>
            <image-preview :src="form.skilled" :width="80" :height="80"/>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="所属场馆">
          <template>
            <span v-if="form.stadiumId==2">东湖昇光店</span>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="技术等级">
          <template>
            <el-tag v-if="form.grade==1">一级</el-tag>
            <el-tag type="success" v-if="form.grade==2">二级</el-tag>
            <el-tag type="warning" v-if="form.grade==3">三级</el-tag>
            <el-tag type="danger" v-if="form.grade==4">四级</el-tag>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="课时费/元">{{ form.price }}元</el-descriptions-item>
        <el-descriptions-item label="入驻时间">{{ form.createAt }}</el-descriptions-item>
        <el-descriptions-item span="4" label="擅长技能">{{ form.major }}</el-descriptions-item>
        <el-descriptions-item span="4" label="授课风格">{{ form.style }}</el-descriptions-item>
        <el-descriptions-item span="4" label="教练介绍">{{ form.introduce }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">关闭</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import { addCoach, delCoach, examine, getCoach, listCoach, updateCoach, updateSort, upStatus } from '@/api/debao/coach'
import { allListStadium } from '@/api/debao/stadium'
import { samelist } from '@/api/system/user'

export default {
  name: 'Coach',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      dialogVisible: false,
      // 总条数
      total: 0,
      // 教练表格数据
      coachList: [],
      isUploadVideo: false,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        stadiumId: null,
        grade: null
      },
      options: [{
        value: '国家一级运动员',
        label: '国家一级运动员'
      }, {
        value: '校队教练',
        label: '校队教练'
      }, {
        value: '二级社会体育指导员',
        label: '二级社会体育指导员'
      }],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '教练姓名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' }
        ],
        label: [
          { required: true, message: '标签不能为空', trigger: 'blur' }
        ],
        avatar: [
          { required: true, message: '头像不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '简单介绍200字以内不能为空', trigger: 'blur' }
        ],
        honor: [
          { required: true, message: '请输入获得荣誉', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '课时费 元/每小时不能为空', trigger: 'blur' }
        ],
        stadiumId: [
          { required: true, message: '所属场馆不能为空', trigger: 'blur' }
        ],
        coachGrade: [
          { required: true, message: '教练等级不能为空', trigger: 'blur' }
        ],
        video: [
          { required: true, message: '短视频不能为空', trigger: 'blur' }
        ]
      },
      /**
       * 场馆列表
       */
      stadiumList: [],
      videoAction: process.env.VUE_APP_BASE_API + '/common/upload',
      videoFileList: [],
      /**
       * 普通用户
       */
      sameList: [],
      coachGrade: [{
        value: 1,
        label: '一级'
      }, {
        value: 2,
        label: '二级'
      }, {
        value: 3,
        label: '三级'
      }, {
        value: 4,
        label: '四级'
      }]
    }
  },
  created() {
    this.getList()
    this.getStadiumList()
    this.getSamelist()

  },
  methods: {
    /** 查询教练列表 */
    getList() {
      this.loading = true
      listCoach(this.queryParams).then(response => {
        this.coachList = response.rows.map(s => {
          s.status = s.status === 1 ? true : false
          return s
        })
        this.total = response.total
        this.loading = false
      })
    },
    //保存草稿箱
    saveDraft() {
      if (!this.form.name && !this.form.phone) {
        this.$message.warning('没有填写任何内容，无法保存草稿！')
        return
      }
      localStorage.setItem('formDraft', JSON.stringify(this.form))
      this.$message.success('草稿已保存！')
    },
    loadDraft() {
      const draft = localStorage.getItem('formDraft')
      if (draft) {
        this.form = JSON.parse(draft)
      }
    },
    /**
     * 上下线教练
     */
    changStatus(e, row) {
      upStatus({
        id: row.id,
        status: e ? 1 : 0
      }).then(res => {
        this.$modal.msgSuccess('更新成功')
      })
    },
    /**
     * 视频上传前
     * @param file
     * @returns {boolean}
     */
    videoBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 10
      if (!isRightSize) {
        this.$message.error('文件大小超过 10MB')
      }
      return isRightSize
    },
    //上传成功后
    videoUploadSuccess(res, file) {
      if (res.code === 200) {
        this.form.video = res.url
      }
    },
    // 删除视频
    videoDelete() {
      this.videoFileList = []
      this.form.video = ''
    },
    // 上传失败
    videoUploadError() {
      this.$modal.msgError('上传图片失败，请重试')
      this.$modal.closeLoading()
    },
    /**
     * 审核
     */
    examineCoach(id, status) {
      examine(id, status).then(res => {
        this.getList()
        this.$modal.msgSuccess('操作成功')
      })
    },
    /**
     * 获取场馆列表
     */
    getStadiumList() {
      allListStadium().then(response => {
        this.stadiumList = response.data
      })
    },
    sortChange(id, sort) {
      updateSort(id, sort).then(res => {
        this.$modal.msgSuccess('排序成功')
        this.getList()
      })
    },
    //选中的普通用户
    sameChange(e) {
      //使用find函数 查询stadiumList中的name
      const user = this.sameList.find(item => {
        return item.userId === e
      })
      if (user) {
        this.form.name = user.userName
      }
    },
    /**
     * 获取普通用户列表
     */
    getSamelist() {
      samelist().then(response => {
        this.sameList = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        name: null,
        avatar: null,
        introduce: null,
        skilled: null,
        major: null,
        style: null,
        price: null,
        status: null,
        stadiumId: null,
        createAt: null,
        updateAt: null,
        label: null
      }
      this.resetForm('form')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.loadDraft() //组件创建时加载草稿箱数据
      this.open = true
      this.videoFileList = []
      this.title = '添加教练'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCoach(id).then(response => {
        this.form = response.data
        this.form.label = this.form.label.split(',')
        this.form.price = this.form.price / 100
        delete this.form.skilledList
        //转换成数组 response.data.video
        this.videoFileList = response.data.video ? [{ url: response.data.video, name: '教练短视频' }] : []
        this.open = true
        this.title = '修改教练'
      })
    },
    handleInfo(row) {
      const id = row.id
      getCoach(id).then(response => {
        this.form = response.data
        this.form.label = this.form.label.split(',')
        delete this.form.skilledList
        this.dialogVisible = true
        this.form.price = this.form.price / 100
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.label = this.form.label.toString()
          this.form.price = this.form.price * 100
          if (this.form.id != null) {
            updateCoach(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCoach(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
        localStorage.removeItem('formDraft') //清除草稿箱数据
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除教练编号为"' + ids + '"的数据项？').then(function() {
        return delCoach(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    }
  }
}
</script>
